<template>
  <a-modal :visible="visible" title="收支流水匹配"
           :okText="modelRef.processApprove?'确定&发起审批':'确定'" @cancel="handleCancel"
           @ok="handleOk" destroy-on-close :width="600"
  >
    <a-alert type="info" v-if="!modelRef.processApprove" style="margin-bottom: 10px;">
      <template #message>
        匹配流水暂未开启审批，点击”
        <span v-if="Approveis_admin" class="link" @click.stop="goSetting">配置</span>
        <span v-else class="link" style="cursor: not-allowed;">配置</span>
        “可快速设置。
      </template>
    </a-alert>
    <div class="content-item">
      <a-row>
        <a-col :span="12" class="text-center">
          <a-statistic title="客户数" :value="owner_count"/>
        </a-col>
        <a-col :span="12" class="text-center">
          <a-statistic title="贷（收入）" :value="amount"/>
        </a-col>
      </a-row>
    </div>

    <div class="content-item " style="margin-bottom: 30px">
      <a-form layout="vertical">
        <a-row :gutter="10">
          <a-col :span="8">
            <a-form-item label="匹配规则">
              <a-select style="width: 100%" placeholder="选择匹配规则"
                        v-model:value="modelRef.rule_id" :options="ruleList"
                        @change="getStaticInfo">
                <template #dropdownRender="{ menuNode: menu }">
                  <v-nodes :vnodes="menu"/>
                  <a-divider style="margin: 4px 0"/>

                  <!--@mousedown="e => e.preventDefault()"  -->
                  <div
                      style="
                          padding: 4px 8px;
                          cursor: pointer;
                          color: #1890ff;
                          text-align: center;
                        "
                      @mousedown="(e) => e.preventDefault()"
                      @click="addRule"
                  >
                    添加
                  </div>
                </template>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item v-bind="validateInfos.pay_date">
              <template #label>
                <span>截止应收/付日期</span>
                <a-tooltip>
                  <template #title>将匹配所有账单的应收/付日期小于等于所选择日期的账单</template>
                  <question-circle-outlined class="ml-5"/>
                </a-tooltip>
              </template>
              <a-date-picker style="width: 100%" v-model:value="modelRef.pay_date"
                             :value-format="dateFormatStr"
                             @change="handleDateChange"/>
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item label="匹配日期" v-bind="validateInfos.match_date">
              <a-date-picker style="width: 100%" v-model:value="modelRef.match_date"
                             :value-format="dateFormatStr"/>
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </div>

    <!--    新增、编辑-->
    <EditMatchRule :visible="addRuleVisible" @toClose="addRuleVisible=false"
                   @success="addSuccess"/>

  </a-modal>
</template>

<script>
import {QuestionCircleOutlined} from '@ant-design/icons-vue'
import {reactive, toRefs, ref, watch} from "vue"
import {Form, message} from "ant-design-vue";
import request from '@/common/utils/request'
import dayjs from 'dayjs'
import store from '@/store'
import EditMatchRule from '@/views/bill/BillTurnover/modules/EditMatchRule.vue'

const useForm = Form.useForm

export default {
  components: {
    EditMatchRule, QuestionCircleOutlined, VNodes: (_, {
      attrs,
    }) => {
      return attrs.vnodes;
    },
  },
  props: {
    visible: {
      type: Boolean,
      default: false
    }
  },
  setup(props, context) {

    const state = reactive({
      ruleList: [],
      owner_count: 0,
      amount: 0,
      Approveis_admin: false,
      Approve_id: 0,
      addRuleVisible: false,

    })

    const modelRef = reactive({
      rule_id: undefined,
      pay_date: "",
      match_date: "",
      processApprove: false,
    })

    const ruleRef = reactive({
      rule_id: [{
        required: false,
        message: ""
      }],
      pay_date: [{
        required: true,
        message: "请选择截止应收/付日期"
      }],
      match_date: [{
        required: true,
        message: "请选择匹配日期"
      }],

    })


    const getStaticInfo = () => {
      const params = {
        rule_id: modelRef?.rule_id,
        pay_date: modelRef?.pay_date
      }
      request.get("/org", "/stream/match/influence", params).then(res => {
        console.log(res)
        const data = res.list;
        state.amount = data.amount;
        state.owner_count = data.owner_count
      })
    }

    const handleDateChange = (dateString) => {
      console.log(dateString)
      getStaticInfo()
    }

    const getRuleList = () => {
      request.get("/org", "/stream/match/all_rules").then(res => {
        console.log(res)
        state.ruleList = res.list.map(item => {
          return {
            label: item.name,
            value: item.id,
          }
        })
      })
    }


    const getSetting = () => {
      // 获取配置
      request.get("/org", "/approval/publish/process", {
        alias: 'bill_stream_match'
      }).then((res) => {
        console.log(res)
        modelRef.processApprove = res.info.process    //判断是否开启
        state.Approveis_admin = res.info.is_admin    //判断是否有权限
        state.Approve_id = res.info.id
      });
    };


    const init = () => {

      getRuleList();
      getSetting();
      // 获取当月最后一天的日期
      const lastDayOfMonth = dayjs().endOf('month').format('YYYY-MM-DD');
      modelRef.pay_date = lastDayOfMonth;
      const toDay = dayjs().endOf('day').format('YYYY-MM-DD');
      modelRef.match_date = toDay;
      getStaticInfo()
    }

    watch(() => props.visible, (value) => {
      if (value) {
        init()
      } else {
        resetFields()
      }
    })

    const addRule = () => {
      state.addRuleVisible = true;
    }
    const addSuccess = () => {
      getRuleList();
      state.addRuleVisible = false;

    }


    const {validate, resetFields, validateInfos} = useForm(modelRef, ruleRef)

    const handleCancel = () => {
      context.emit("toCancel")
    }

    const handleOk = () => {
      validate().then(() => {
        const params = {
          ...modelRef
        }
        if (!modelRef.rule_id) {
          delete params.rule_id;
        }
        console.log(params)
        request.post("/org", "/stream/match/key", params).then(res => {
          console.log(res)
          message.success("操作成功！")
          resetFields()
          context.emit("toCancel")
        })
      })
    }

    const goSetting = () => {
      if (window.__MICRO_APP_ENVIRONMENT__) {

        window.microApp.forceDispatch({
          type: "SetChildDrawerList",
          info: {
            props: {
              title: "审批设置",
              maskCloseable: true,
              visible: true,
              closable: true,
              width: 1200,
              bodyStyle: {padding: 0, background: '#f7f7f7', height: '100%'},
              destroyOnClose: true,
            },
            microId: "approval_ApprovalSettings",
            app: "workApproval",
            url: '/approval/ApprovalSettings',
            params: {
              id: state.Approve_id,
              isMainDrawer: true,
              closeApproval: () => {
                getSetting()
              }
            }
          },

        })
      }

    };

    return {
      modelRef,
      handleCancel,
      handleOk,
      validateInfos,
      ...toRefs(state),
      handleDateChange,
      dateFormatStr: "YYYY-MM-DD",
      getStaticInfo,
      goSetting,
      addRule,
      addSuccess,

    }
  }
}
</script>

<style lang="less" scoped>
.content-item {
  border: 1px solid #eeeeee;
  margin-top: 20px;
  padding: 10px 30px;

  .text-center:not(:last-child):after {
    content: "";
    position: absolute;
    right: 0;
    top: 25%;
    height: 50%;
    border-left: 1px solid #e6e5e5;
  }

}


</style>